package com.zzld.modules.sys.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.zzld.core.service.BaseServiceImpl;
import com.zzld.core.utils.UuidUtil;
import com.zzld.modules.sys.entity.Res;
import com.zzld.modules.sys.entity.RoleRes;
import com.zzld.modules.sys.mapper.RoleResMapper;
import com.zzld.modules.sys.service.IRoleResService;

@Service("roleResService")
public class RoleResServiceImpl  extends BaseServiceImpl<RoleRes> implements IRoleResService{

	@Autowired
	private RoleResMapper roleResMapper;

	/**
	 * 根据用户ID获取用户菜单资源
	 * 
	 * @param uid
	 *            用户ID
	 * @return
	 */
	public List<Res> getUserRes(String uid) {
		List<Res> resList = null;
		try {
			resList = roleResMapper.getUserRes(uid);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		return resList;
	}
	

	/**
	 * 根据用ID和父ID获取数据
	 * 
	 * @param uid
	 * @param rid
	 * @return
	 */
	public List<Res> getResTreeById(String uid, String pid) {
		List<Res> resList = null;
		Map<String, Object> parameMap = new HashMap<String, Object>();
		if (pid.equals("")) {
			pid = null;
		}
		if (uid == null) {
			return null;
		}
		parameMap.put("uid", uid);
		parameMap.put("pid", pid);
		try {
			if (pid == null) {

				resList = roleResMapper.getResTreeByIdIsnull(parameMap);
			} else {
				resList = roleResMapper.getResTreeById(parameMap);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		return resList;
	}

	/**
	 * 根据id获取角色资源表
	 * 
	 * @param
	 */
	public List<RoleRes> selebykey(String role_id) {
		if (role_id != null) {
			return (List<RoleRes>) roleResMapper.selectByPrimaryKey(role_id);
		}
		return null;
	}

	/**
	 * 修改角色权限
	 * 
	 * @param
	 */
	public int updateRoleRes(String id, String ids) {
		List<RoleRes> list = roleResMapper.selectbyroleid(id);
		byte u = 0;
		if (list != null) {
		  for(RoleRes q:list){
			  if(roleResMapper.deleteByPrimaryKey(q.getId())==0){
				  u=1;
				  break;
			  }
		  }
		}

		RoleRes rq = new RoleRes();
		
		for (String w : ids.split(",")) {
			rq.setId(UuidUtil.uuid().toString());
			rq.setRoleId(id);
			rq.setResId(w);
			if (roleResMapper.insert(rq) == 0) {
				u = 1;
				break;
			}
			
		}
		if (u != 0) {
			return 0;
		}
		return 1;

	}

}
